package net.jxta.myjxta.plugins.tictactoe;

import net.jxta.endpoint.Message;
import net.jxta.myjxta.MyJXTA;
import net.jxta.myjxta.dialog.*;
import net.jxta.myjxta.plugin.IPluginNotificationHandler;
import net.jxta.myjxta.plugin.ISelectableNode;
import net.jxta.myjxta.plugin.PluginBase;
import net.jxta.myjxta.plugin.PluginContainer;
import net.jxta.myjxta.plugins.tictactoe.commands.TicTacToeCommand;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Resources;
import net.jxta.myjxta.util.objectmodel.JxtaNode;
import net.jxta.myjxta.util.objectmodel.PeerNode;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ResourceBundle;

/**
 * This Plugin provides the TicTacToe game
 * It does:
 * - register the TicTacToeCommand in the command factory (so that this peer can react on external play requests)
 * - registers the DialogNamer (dont understand the full concept behind the namer)
 * - registers a dialog provider (the provider creates the dialog on an incomming bidi-pipe request)
 * - registers a popup provider that adds a "TicTacToe" action in the peer action menu (to initiate the game with another peer)
 */
public class TicTacToePlugin extends PluginBase implements IPluginNotificationHandler, PluginContainer.IPopupProvider, DialogManager.IDialogProvider {

    private static final ResourceBundle STRINGS = Resources.getStrings();

    public TicTacToePlugin() {
        LOG.log(java.util.logging.Level.INFO, "TicTacToePlugin Constructor called");
        setName(STRINGS.getString("menu.peer.tictactoe"));
    }

    public IPluginNotificationHandler getPluginNotificationHander() {
        return this;
    }

    public void init(PluginContainer c) {
        super.init(c);

        //register the TicTacToeCommand so that it is recognised during incoming connections
        CommandFactory.registerCommand(TicTacToeCommand.class);

        //nano: maybe we should consolidate DialogNamer and DialogProvider?
        //register the dialog namer (this will provide the name for the pipe-advertisments)
        Dialog.registerDialogNamer(TicTacToeDialog.class, new DialogNamer() {
            public String getDialogName(String s) {
                return TicTacToeDialog.DIALOG_NAME +
                        Dialog.IMFREE_DELIMITER + s;
            }
        });

        //this tells the DialogManager that we are able to instantiate a TicTacToeDialog
        DialogManager.registerDialogProvider(TicTacToeDialog.class, this);

        //we have to contribute the "TicTacToe" menuentry, so register this plugin as a popup provider
        m_container.registerPopupProvider(this);

        start(); //autostart - we want the menu entry immediately after the initialisation

    }


    public void destroy() {
        CommandFactory.unregisterCommand(TicTacToeCommand.class);
    }

    public void groupJoined(final Group p_group) {
        //on any group join we register our dialog name (--> dialog bidi-pipe) at the
        //correct dialogmanager
        if (!p_group.isVisible()) //no listeners for npg and other non-visible groups
            return;


        String dialogName1;
        PeerGroup pg = p_group.getPeerGroup();
        dialogName1 = Dialog.getDialogNamer(TicTacToeDialog.class).
                getDialogName(pg.getPeerName());

        final MyJXTA myJxta = m_container.getMyJxta();
        myJxta.setStatus(STRINGS.getString("status.dialog.listener.add") +
                ": " + dialogName1);

        // if we  get an incomming bidi-pipe request....
        DialogManager.getInstance(p_group, dialogName1, PipeService.UnicastType).
                addPipeListener(pg, new DialogPipeListener() {
                    // xxx: authenticate if not. for now, we are authenticated

                    public void receive(PeerGroup pg11, JxtaBiDiPipe pipe) {
                        myJxta.addDialog(DialogManager.getDialog(TicTacToeDialog.class,
                                p_group, pipe, myJxta));
                    }

                    public void receive(PeerGroup pg11, Message msg) {
                    }
                });
    }

    public void groupResigned(Group p_group) {

        if (!p_group.isVisible())
            return;
        //remove tictactoe
        String pn = Dialog.getDialogNamer(TicTacToeDialog.class).getDialogName(p_group.getPeerGroup().getPeerName());

        m_container.getMyJxta().setStatus(STRINGS.getString("status.dialog.listener.remove") +
                ": " + pn);

        DialogManager.getInstance(p_group, pn, PipeService.UnicastType).
                clearPipeListeners(p_group.getPeerGroup());
        //end tictactoe
    }

    public void groupStateChanged(Group p_group) {
        //nothing in here - this method is called if we get connected/disconnected from a joined group
        //we could possibly activate/deactivate the menu here....
    }


    public void popupRequested(PluginContainer.IPopupGenerator popupGenerator, ISelectableNode[] selectedNodes, MouseEvent triggerEvent) {

        if (!isRunning())
            return;
        if (selectedNodes != null && selectedNodes.length >= 1) {
            JxtaNode jxtaNode = selectedNodes[0].getJxtaNode();
            if (jxtaNode instanceof PeerNode) {
                PluginContainer.MenuPath peerPath = new PluginContainer.MenuPath(Resources.getStrings().getString("menu.peer"), KeyEvent.VK_P);

//                Group g=((GroupNode)  MyJxtaObjectRepository.getObjectRepository().getParent(peerNode)).getGroup();
//                popupGenerator.addPopup(new PluginContainer.MenuPath[]{peerPath}, 8, new TicTacToeInviteAction(m_name, m_container.getMyJxta().getView()));
            }
        }
    }

    public Dialog createDialog(Group p_g, PipeAdvertisement p_pa, MyJXTA p_myjxta) {
        return new TicTacToeDialog(p_g, p_pa, p_myjxta);
    }

    public Dialog createDialog(Group p_g, JxtaBiDiPipe p_pipe, MyJXTA p_myjxta) {
        return new TicTacToeDialog(p_g, p_pipe, p_myjxta);
    }
}
